package email

import (
	"github.com/jordan-wright/email"
	"github.com/sirupsen/logrus"
	"net/smtp"
)

var gm *Mail

func GetMail() *Mail {
	if gm == nil {
		gm = &Mail{}
	}
	return gm
}

type Mail struct {
	user        string   //用户
	password    string   //密码
	host        string   //主机
	To          []string //发送方
	Cc          []string //抄送方
	Bcc         []string //秘密抄送方
	Subject     string   //主题
	Content     string   //内容
	contentType string
}

func (m *Mail) Init(user string, pass string, host string) *Mail {
	gm = &Mail{
		user:     user,
		password: pass,
		host:     host,
	}
	return gm
}
func (m *Mail) SetContent(content string) *Mail {
	m.Content = content
	return m
}

func (m *Mail) SetSubject(subject string) *Mail {
	m.Subject = subject
	return m
}
func (m *Mail) SetCc(cc []string) *Mail {
	m.Cc = cc
	return m
}
func (m *Mail) SetBcc(bcc []string) *Mail {
	m.Bcc = bcc
	return m
}
func (m *Mail) Send(to []string) (err error) {
	m.To = to
	err = m.s()
	return
}
func (m *Mail) SendHtml(to []string) (err error) {
	m.contentType = "html"
	m.To = to
	err = m.s()
	return
}
func (m *Mail) s() error {
	e := email.NewEmail()
	//设置发送方的邮箱
	e.From = m.user
	// 设置接收方的邮箱
	e.To = m.To
	//设置抄送如果抄送多人逗号隔开
	e.Cc = m.Cc
	//设置秘密抄送
	e.Bcc = m.Bcc
	//设置主题
	e.Subject = m.Subject
	//设置文件发送的内容
	if m.contentType == "html" {
		e.HTML = []byte(m.Content)
	} else {
		e.Text = []byte(m.Content)
	}
	//设置服务器相关的配置
	err := e.Send(m.host+":25", smtp.PlainAuth("", m.user, m.password, m.host))
	if err != nil {
		logrus.Error(err)
	}
	return err
}
